package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int32  `mapstructure:"port"`
}

type ServerConfig struct {
	ServerName  string      `mapstructure:"name"`
	Port        int32       `mapstructure:"port"`
	MysqlConfig MysqlConfig `mapstructure:"mysql"`
}

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}
func main() {
	info := GetEnvInfo("DEBUG")
	fmt.Println(info)
	v := viper.New()
	v.SetConfigFile("viper_test/config.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	sc := ServerConfig{}
	if err := v.Unmarshal(&sc); err != nil {
		panic(err)
	}
	fmt.Println(sc)
	//viper的功能 动态监听配置的变化
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file changed:", in.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&sc)
	})
}
